package com.sap.apitest2.common;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class APIDefinition {
	private String URIPattern;
	private String URI;


	private String[] param;
	private String mtd;
	private String format;
	
	private List<DefaultTestCase> testCases ;

	public List<DefaultTestCase> getTestCases() {
		if(testCases!=null)
			return Collections.unmodifiableList(testCases);
		else
			return Collections.emptyList();
	}


	private static List<APIDefinition> APIDefinitionList = new ArrayList<APIDefinition>();
	
	public static List<APIDefinition> getAPIDefinitionList() {
		return Collections.unmodifiableList(APIDefinitionList);
	}



	public synchronized boolean addTaestCase(DefaultTestCase e) {
		if(testCases==null)
			this.testCases = new ArrayList<DefaultTestCase>(); 
		
		return testCases.add(e);
	}



	public APIDefinition(String URIPattern) {
		super();
		this.URIPattern = URIPattern;
		parseURIPattern(URIPattern);
		synchronized(APIDefinitionList) {
			APIDefinitionList.add(this);
		}
	}
	

	
	public String getURIPattern() {
		return URIPattern;
	}
	public String[] getParam() {
		return param;
	}
	public String getMtd() {
		return mtd;
	}
	public String getFormat() {
		return format;
	}
	public String getURI() {
		return URI;
	}


	private void parseURIPattern(String URIPattern) {
		;
		List<String> list = new ArrayList<String>();
		String tagregex = "<[^>]*>|\\[[^\\]]*\\]";
		Pattern p2 = Pattern.compile(tagregex);
		Matcher m2 = p2.matcher(URIPattern);
		while (m2.find()) {
			String group = m2.group();
			list.add(group.substring(1, group.length()-1));
		}
		this.URI = URIPattern;
		format = list.get(list.size()-1);
		list.remove(list.size()-1);
		this.URI = this.URI.replaceAll("\\["+format+"\\]", "");
		mtd = list.get(list.size()-1);
		list.remove(list.size()-1);
		this.URI = this.URI.replaceAll("\\["+mtd+"\\]", "");
		param = list.toArray(new String[]{});
	}
}
